// import dayjs from "dayjs";
import { message } from "@/utils/message";
import { getRoleList, getRoleUpdate, getRoleDelete } from "@/api/user";
import { dividerProps, ElMessageBox, formatter } from "element-plus";
import { useRouter } from "vue-router";
import { delay, useWatermark } from "@pureadmin/utils";
import { useUserStoreHook } from "@/store/modules/user";
import { sessionKey } from "@/utils/auth";
import type { PaginationProps, LoadingConfig } from "@pureadmin/table";
import { storageSession } from "@pureadmin/utils";
import { initRouter } from "@/router/utils";
import * as CryptoJS from "crypto-js";
import { getSessionKey } from "@/utils/auth";
import { reactive, ref, computed, onMounted, inject } from "vue";
import { roleList, delAsyncRoutes } from "@/api/routes";
// import { number } from "echarts/core";
import { companyList, companyDelete } from "@/api/companyList";
import { log } from "console";
console.log(import.meta.env.VITE_PROXY_TARGET);

const baseUrl = window.location.origin;
export function useRole(waterRef: Ref) {
  const dataList = ref([]);
  const loading = ref(true);
  const switchLoadMap = ref({});
  const router = useRouter();
  const refresh: any = inject("reload");
  interface StorageConfigs {
    role_id: number;
  }
  /** 分页配置 */
  const pagination = reactive<PaginationProps>({
    pageSize: 10,
    currentPage: 1,
    pageSizes: [10, 20, 30],
    total: 0,
    align: "right",
    background: true,
    small: false
  });

  /** 加载动画配置 */
  const loadingConfig = reactive<LoadingConfig>({
    text: "正在加载第一页...",
    viewBox: "-10, -10, 50, 50",
    spinner: `
        <path class="path" d="
          M 30 15
          L 28 17
          M 25.61 25.61
          A 15 15, 0, 0, 1, 15 30
          A 15 15, 0, 1, 1, 27.99 7.5
          L 15 15
        " style="stroke-width: 4px; fill: rgba(0, 0, 0, 0)"/>
      `
    // svg: "",
    // background: rgba()
  });
  const columns: TableColumnList = [
    {
      type: "selection",
      width: 55,
      align: "left",
      hide: ({ checkList }) => !checkList.includes("勾选列")
    },
    {
      label: "序号",
      type: "index",
      width: 70,
      hide: ({ checkList }) => !checkList.includes("序号列")
    },

    {
      label: "ID",
      prop: "id",
      minWidth: 70
    },
    {
      label: "公司名",
      prop: "name",
      minWidth: 200,
      formatter: ({ name, tax_code }) => {
        return (
          <div>
            {name ? <div>{name} </div> : ""}
            {tax_code ? <div>{tax_code}</div> : ""}
          </div>
        );
      }
    },
    {
      label: "法人代表",
      minWidth: 180,
      prop: "legal_name",
      formatter: row => {
        return (
          <div>
            <el-tag class="mx-1" type="success" effect="light">
              {row.legal_name}
            </el-tag>
          </div>
        );
      }
    },
    {
      label: "股东",
      minWidth: 180,
      prop: "shareholder_array",
      formatter: row => {
        if (!row.shareholder_array) {
          return null;
        }
        return (
          <div>
            {row.shareholder_array.map((item, index) => (
              <div key={index}>
                <el-tag class="mx-1" type="success" effect="light">
                  {item.type == 1 ? item.peo_name : item.com_name}
                </el-tag>
              </div>
            ))}
          </div>
        );
      }
      //peo_name
    },
    {
      label: "高管",
      minWidth: 180,
      prop: "officer_name",
      formatter: row => {
        return (
          <div>
            <el-tag class="mx-1" type="success" effect="light">
              {row.officer_name}
            </el-tag>
          </div>
        );
      }
    },
    {
      label: "税务等级 ",
      prop: "tax_level",
      minWidth: 100,
      formatter: row => {
        let str = "";
        switch (row.tax_level) {
          case 1:
            str = "小规模";
            break;
          case 2:
            str = "一般纳税人";
            break;
          default:
            break;
        }
        return str;
      }
    },
    {
      label: "注册资金(万元)",
      prop: "register_fund",
      minWidth: 150
    },
    {
      label: "企业成立时间",
      prop: "establish_time",
      minWidth: 150,
      formatter: ({ establish_time, address }) => {
        return (
          <div>
            {establish_time ? <div>{establish_time} </div> : ""}
            {address ? <div>{address}</div> : ""}
          </div>
        );
      }
    },
    {
      label: "经营范围",
      prop: "business",
      minWidth: 150
    },
    {
      label: "创建时间",
      minWidth: 180,
      prop: "create_time"
    },

    {
      label: "操作",
      fixed: "right",
      width: 240,
      slot: "operation"
    }
  ];

  const childColumns: TableColumnList = [
    {
      label: "ID",
      prop: "id",
      minWidth: 70
    },
    {
      label: "股东",
      prop: "id",
      minWidth: 70,
      formatter: ({ type, peo_name, com_name }) => {
        return (
          <div>
            {type == 1 ? <div>{peo_name} </div> : <div>{com_name} </div>}
          </div>
        );
      }
    },
    {
      label: "出资比例 ",
      prop: "fund_ratio",
      minWidth: 70
    },
    {
      label: "认缴金额(万元)",
      prop: "subscribe_money",
      minWidth: 70
    },
    {
      label: "认缴日期",
      prop: "subscribe_time",
      minWidth: 70
    },
    {
      label: "实缴金额(万元)",
      prop: "practical_money",
      minWidth: 70
    },
    {
      label: "创建时间 ",
      prop: "create_time",
      minWidth: 70
    }
  ];
  const buttonClass = computed(() => {
    return [
      "!h-[20px]",
      "reset-margin",
      "!text-gray-500",
      "dark:!text-white",
      "dark:hover:!text-primary"
    ];
  });
  function onChange({ row, index }) {
    console.log(row, index);
    ElMessageBox.confirm(
      `确认要<strong>${
        row.status === 0 ? "启用" : "停用"
      }</strong><strong style='color:var(--el-color-primary)'>${
        row.name
      }</strong>人员吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(() => {
        switchLoadMap.value[index] = Object.assign(
          {},
          switchLoadMap.value[index],
          {
            loading: true
          }
        );
        const rowValue = {
          admin_id: row.admin_id,
          admin_status: row.admin_status
        };
        const rowJson = JSON.stringify(rowValue);
        // 对JSON字符串进行Base64加密
        // const encryptedFormIsRef = CryptoJS.enc.Base64.stringify(
        //   CryptoJS.enc.Utf8.parse(rowJson)
        // );
        // const rowtype = {
        //   value: encryptedFormIsRef
        // };
        const res = getUpdate(rowValue);
        console.log(res);
        setTimeout(() => {
          switchLoadMap.value[index] = Object.assign(
            {},
            switchLoadMap.value[index],
            {
              loading: false
            }
          );
          message("已成功修改人员状态", {
            type: "success"
          });
        }, 300);
      })
      .catch(() => {
        row.status === 1 ? (row.status = 2) : (row.status = 1);
      });
  }
  /**修改角色状态 */
  async function handleUpdate(row) {
    const res = getRoleUpdate(row);
    console.log(row, res);
  }
  /**删除角色 */
  async function handleDelete(row) {
    const idname = { id: row.id };
    // const idnameJson = JSON.stringify(idname);
    // const idnameBase64 = CryptoJS.enc.Base64.stringify(
    //   CryptoJS.enc.Utf8.parse(idnameJson)
    // );
    // const idnameValue = {
    //   value: idnameBase64
    // };
    const res = await companyDelete(idname);
    if (res.code == 200) {
      message("删除成功", { type: "success" });
      refresh();
    } else {
      message(res.msg, { type: "error" });
    }
  }
  function handleaddUser() {
    console.log("dshfjskdhf");
  }
  function handleSizeChange(val: number) {
    console.log(`${val} items per page`);
    pagesize.value = val;
    getList();
  }

  function handleCurrentChange(val: number) {
    page.value = val;
    getList();
    console.log(`current page: ${val}`);
  }

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }

  function onCurrentChange(val) {
    loadingConfig.text = `正在加载第${val}页...`;
    loading.value = true;
    delay(600).then(() => {
      loading.value = false;
    });
  }

  //搜索
  async function onSearch(formIs) {
    loading.value = true;
    const params = {
      ...formIs,
      page: page.value,
      pagesize: pagesize.value
    };
    const { data } = await companyList(params);
    dataList.value = data.data;

    pagination.total = data.total;
    setTimeout(() => {
      loading.value = false;
    }, 500);
  }
  const pagesize = ref(10);
  const page = ref(1);
  //获取数据
  async function getList() {
    const params = {
      pagesize: pagesize.value,
      page: page.value,
      name: "",
      tax_level: "",
      legal: "",
      action: action.value,
      admin_id: getSessionKey().admin_id,
      role_id: getSessionKey().role_id
    };
    const res = await companyList(params);
    if (res.code === 200) {
      dataList.value = res.data.data;
      console.log(dataList.value, "参数的");
      pagination.total = res.data.total;
      setTimeout(() => {
        loading.value = false;
      }, 500);
    } else {
      message(res.msg, { type: "error" });
    }
  }
  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    location.reload();
  };
  const action = ref("");
  const handleRadio = val => {
    action.value = val;
    getList();
  };
  onMounted(() => {
    delay().then(() => {
      // https://pure-admin-utils.netlify.app/hooks/useWatermark/useWatermark.html
      const { setWatermark } = useWatermark(
        waterRef.value.getTableDoms().tableWrapper
      );
      //水印
      setWatermark("后台项目", {
        font: "16px Microsoft YaHei",
        globalAlpha: 0.8,
        forever: true,
        width: 252,
        height: 80
      });
    });
    getList();
  });

  return {
    loading,
    columns,
    childColumns,
    dataList,
    pagination,
    buttonClass,
    onSearch,
    getList,
    resetForm,
    handleaddUser,
    handleUpdate,
    handleDelete,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange,
    onCurrentChange,
    handleRadio
  };
}
